<template>
  <view>
    <uni-popup ref="chooseDate" type="bottom" background-color="#fff" @change="bindClose">
      <view class="popup-content" style="height: 630rpx" v-if="showState">
        <view class="downs" @click="bindClose($event, 1)">
          <view class="downs-btn"></view>
          <view class="">选择时间</view>
        </view>
        <picker-view class="picker-view" :indicator-style="indicatorStyle" :value="selectValue" @change="bindChange">
          <picker-view-column :style="dateCurr === 2 ? 'flex:0 0 200rpx;' : ''">
            <view class="item" v-for="(item, index) in years" :key="index">{{ item }}年</view>
          </picker-view-column>
          <picker-view-column>
            <view class="item" v-for="(item, index) in months" :key="index">
              {{ item }}月
              <text style="right: 27%" v-if="nowYear == year && item == monthsCur && dateCurr === 3">本月</text>
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="item day" v-for="(item, index) in days" :key="index">
              <view class="date-left"> {{ item }}日 </view>

              <text class="todayStr" v-if="item == daysCur">今日</text>
              <text class="todayStr" v-if="item == tomorrow">明天</text>
              <text class="todayStr" v-if="item == afterTomorrow">后天</text>

            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="item" v-for="(item, index) in hours" :key="index">{{ item > 9 ? item : "0" + item }}
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="item" v-for="(item, index) in minutes" :key="index">
              {{ item > 9 ? item : "0" + item }}
            </view>
          </picker-view-column>
          <view class="colon">:</view>
        </picker-view>
        <view class="bottoms">
          <view class="reSet" @click="bindClose($event, 1)">取消</view>
          <view class="submit" @click="submitDate">确认</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import dayjs from 'dayjs';
export default {
	name: 'weekYearDate',
	data() {
		return {
			monthsCur: dayjs().format('MM'),
			daysCur: dayjs().format('DD'),
			// weekCur: getWeeks(dayjs().format("YYYY-MM-DD")),
			nowYear: new Date().getFullYear(),
			years: [],
			year: new Date().getFullYear(),
			months: [],
			month: '',
			days: [],
			hours: [],
			minutes: [],
			day: '',
			tomorrow: '',
			afterTomorrow: '',
			// weekList: [], //年周数据
			// weekIndex: null, //周下标
			selectDate: null, // 日期选择数据
			selectValue: [], // 日期选择
			indicatorStyle: `color: #0091ff;height: ${Math.round(
				uni.getSystemInfoSync().screenWidth / (950 / 100)
			)}px;`,
		};
	},
	watch: {
		showState(val) {
			if (val) {
				this.getTimes();
			}
		},
		selectValue(val) {
			// console.log(val);
			// let orginYear = this.years[val[0]];
			// let orginMonth = this.months[val[1]];
			// let orginDay = this.days[val[2]];
			// let orginHour = this.hours[val[3]];
			// let orginMin= this.minutes[val[4]];
			// console.log(orginYear,orginMonth, orginDay,orginHour,orginMin,"666");
		},
	},
	props: {
		dateCurr: { type: [String, Number], default: 1 },
		showState: {
			type: Boolean,
			default: false,
		},
	},

	methods: {
		setWeekList(year) {
			let arrWeek = this.getAllWeekRange(year) || [];
			let arr = [];
			for (let i = 1; i <= arrWeek.length; i++) {
				// console.log("arrarr",i,arrWeek[i-1])
				if (
					arrWeek[i - 1].value <= getWeeks(dayjs().format('YYYY-MM-DD')) ||
          year < this.nowYear
				) {
					arr.push({ ...arrWeek[i - 1] });
				}
				// arr.push({ ...arrWeek[i - 1] })
			}
			this.weekList = arr;
		},
		// 关闭
		bindClose(e, type) {
			if (!e.show) {
				this.$emit('bindClose', false);
			}
			if (type === 1) {
				this.$emit('bindClose', false);
			}
		},
		// 日期选择
		bindChange(e) {
			let val = e.detail.value;
			let year = this.years[val[0]];
			this.setMonth(year);
			let month = this.months[val[1]];
			let days = [];
			let day = this.days[val[2]];
			let monthDays = this.solarDays(year, month); // 获取每月日数
			const curDays = new Date().getDate();
			let hour = this.hours[val[3]];
			let minute = this.minutes[val[3]];
			let hours = [];
			let minutes = [];
			let currentMonth =
        month == new Date().getMonth() + 1 && year == this.nowYear;
			if (month == new Date().getMonth() + 1 && year == this.nowYear) {
				// 当月获取当前天数
				for (let i = curDays; i <= monthDays; i++) {
					days.push(i);
				}
				this.days = days;
				this.daysCur = dayjs().format('DD');
				this.tomorrow =
          new Date().getDate() + 1 > 9
          	? new Date().getDate() + 1
          	: '0' + new Date().getDate() + 1;
				this.afterTomorrow =
          new Date().getDate() + 2 > 9
          	? new Date().getDate() + 2
          	: '0' + new Date().getDate() + 2;
				// 如果是今日
				if (new Date().getDate() == this.days[val[2]] && currentMonth) {
					// 判断是否同一个小时
					for (let c = new Date().getHours(); c <= 23; c++) {
						hours.push(c);
					}
					this.hours = hours;
					if (new Date().getHours() == this.hours[val[3]]) {
						// 如果是同一个小时只要以后的
						// console.log("同一个小时");
						for (let c = new Date().getMinutes(); c <= 59; c++) {
							minutes.push(c);
						}
						this.minutes = minutes;
					} else {
						this.minutes = Array.from({ length: 60 }, (v, k) => k);
					}
				} else {
					// console.log("不是今日");
					this.minutes = Array.from({ length: 60 }, (v, k) => k);
					this.hours = Array.from({ length: 24 }, (v, k) => k);
				}

				// if (new Date().getDate() == day && currentMonth) {
				//   console.log("是今日");
				//   for (let i = new Date().getHours(); i <= 59; i++) {
				//     hours.push(i);
				//     this.hours = hours;
				//   }
				//   if (new Date().getHours() == hour && currentMonth) {
				//     console.log("同一个小时");
				//     for (let i = new Date().getMinutes(); i <= 59; i++) {
				//       minutes.push(i);
				//       this.minutes = minutes;
				//     }
				//   } else {
				//     this.minutes = Array.from({ length: 60 }, (v, k) => k).slice(1);
				//   }
				// } else {
				//   for (let i = 1; i <= 59; i++) {
				//     hours.push(i);
				//     this.hours = hours;
				//   }
				// }
			} else {
				for (let c = 1; c <= monthDays; c++) {
					days.push(c);
				}
				this.days = days;
				this.hours = Array.from({ length: 23 }, (v, k) => k);
				// this.hours = hours;
				minutes = Array.from({ length: 60 }, (v, k) => k);
				this.minutes = minutes;
				this.daysCur = 32;
				this.tomorrow = '';
				this.afterTomorrow = '';
			}

			// this.selectDate =
			//   year +
			//   "/" +)
			//   (month < 10 ? "0" + month : month) +
			//   "/" +
			//   (day < 10 ? "0" + day : day);
			const h = this.hours[val[3]];
			const min = this.minutes[val[4]];
			this.selectDate = `${this.years[val[0]]}-${this.zeroFilling(
				this.months[val[1]]
			)}-${this.zeroFilling(this.days[val[2]])} ${this.zeroFilling(h)}:${this.zeroFilling(
				min
			)}`;
		},
		// 补零
		zeroFilling(str) {
			return str >= 10 ? str : '0' + str;
		},
		// 年月的天数
		solarDays: function (y, m) {
			let solarMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
			if (m > 12 || m < 1) {
				return -1;
			} // 若参数错误 返回-1
			var ms = m - 1;
			if (ms == 1) {
				// 2月份的闰平规律测算后确认返回28或29
				return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 ? 29 : 28;
			} else {
				return solarMonth[ms];
			}
		},
		// 初始日期
		getTimes() {
			const date = new Date();
			const years = [];
			const year = date.getFullYear();
			const month = new Date().getMonth() + 1;
			const days = [];
			const day = date.getDate();
			const hours = [];
			const hour = date.getHours();
			const minutes = [];
			const minute = date.getMinutes();
			let yearsCount = date.getFullYear();

			for (let i = date.getFullYear(); i <= yearsCount + 1; i++) {
				years.push(i);
			}
			this.years = years;
			this.setMonth(year);

			let monthDays = this.solarDays(year, month); // 每月日数
			for (let c = day; c <= monthDays; c++) {
				days.push(c);
			}
			this.days = days;
			if (month == new Date().getMonth() + 1 && year == this.nowYear) {
				this.daysCur = dayjs().format('DD');
			} else {
				this.daysCur = 32;
			}
			if (month == new Date().getMonth() + 1 && year == this.nowYear) {
			}
			for (let h = hour; h <= 23; h++) {
				hours.push(h);
			}
			this.hours = hours;
			for (let m = minute; m <= 59; m++) {
				minutes.push(m);
			}
			this.minutes = minutes;
			let yeari = this.years.findIndex(
				(item) => item == Number(dayjs().format('YYYY'))
			);

			let monthi = this.months.findIndex(
				(item) => item == Number(dayjs().format('MM'))
			);

			let dayi = this.days.findIndex(
				(item) => item == Number(dayjs().format('DD'))
			);
			this.selectValue = [yeari, monthi, dayi, 0, 0];
			let val = this.selectValue;
			this.selectDate = `${this.years[val[0]]}-${this.zeroFilling(
				this.months[val[1]]
			)}-${this.zeroFilling(this.days[val[2]])} ${this.zeroFilling(this.hours[val[3]])}:${this.zeroFilling(
				this.minutes[val[4]]
			)}`;
		},

		setMonth(year) {
			const nowYear = new Date().getFullYear();
			let months = [];
			let month = 12; //
			if (year == nowYear) {
				month = new Date().getMonth() + 1;
				for (let j = month; j <= 12; j++) {
					months.push(j);
				}
			} else {
				for (let j = 1; j <= 12; j++) {
					months.push(j);
				}
			}

			this.months = months;
		},

		// 通过年获取 本年周数  year 年
		getWeekNum(year) {
			const firstDay = new Date(parseInt(year), 0, 1).getDay(), // 设置该年1.1星期
				endDay = new Date(parseInt(year), 11, 31).getDay(); // 设置该年12.31星期

			// 该年最大周次.1.1.在周一到周四,则为该年第一周,否则为上年最后一周.
			const flag =
        firstDay >= 1 &&
        firstDay <= 4 &&
        (endDay == 0 || endDay == 4 || endDay == 5 || endDay == 6);
			// 1.1.和12.31.都在本年,则该年有53周,否则52周
			const maxWeek = flag ? 53 : 52;
			return maxWeek;
		},
		// 通过年份、周数获取日期范围   year 年   weeks 周  getWeekRange(2019,12))--> 2019-03-18~2019-03-24
		// 参数:type 日期是否补零 默认日期补零
		getWeekRange(year, weekNum, type = 1) {
			const yearStart = new Date(parseInt(year), 0, 1), // 设置该年1.1.
				firstDay = yearStart.getDay(); // 星期
			// 对1.1.所在周的前后几天特殊处理.
			const other =
        firstDay >= 0 && firstDay <= 4 ? firstDay - 1 : firstDay - 8;

			// 时间调整,得出要计算周的起/始时间.
			// 考虑距离当年1.1.的总天数
			let days = (parseInt(weekNum, 10) - 1) * 7 - other;
			// 一天时间的毫秒数
			let oneDay = 24 * 60 * 60 * 1000;

			// 当前周 第一天 离1/1/70的毫秒数.
			let dateInMs = oneDay * days + yearStart.getTime();
			// 日期调整(设置1/1/70至今的毫秒数)
			const weekStart = new Date(dateInMs);

			// 当前所选周最后一天处理,同上.
			let dateInMsE = oneDay * 6 + dateInMs;
			const weekEnd = new Date(dateInMsE);

			// 月和日的处理,一位变两位,如:1->01.
			let month = weekStart.getMonth() + 1;
			let day = weekStart.getDate();

			let monthE = weekEnd.getMonth() + 1;
			let dayE = weekEnd.getDate();

			if (type === 1) {
				month = month < 10 ? '0' + month : month;
				day = day < 10 ? '0' + day : day;
				monthE = monthE < 10 ? '0' + monthE : monthE;
				dayE = dayE < 10 ? '0' + dayE : dayE;
			}

			// return (weekStart.getFullYear() + "-" + month + "-" + day) + "~" + (weekEnd.getFullYear() + "-" + monthE + "-" + dayE)
			return (
				month +
        '月' +
        '' +
        day +
        '日' +
        '-' +
        (monthE + '月' + '' + dayE + '日')
			);
			// return (month + day) + "-" + (monthE + dayE)
		},
		// 根据具体日期，获取当天所在周的周数
		getYearWeek(dateString) {
			var da = dateString; // 日期格式2015-12-30
			// 当前日期
			var date1 = new Date(
				da.substring(0, 4),
				parseInt(da.substring(5, 7)) - 1,
				da.substring(8, 10)
			);
			// 1月1号
			var date2 = new Date(da.substring(0, 4), 0, 1);
			// 获取1月1号星期（以周一为第一天，0周一~6周日）
			var dateWeekNum = date2.getDay() - 1;
			if (dateWeekNum < 0) {
				dateWeekNum = 6;
			}
			if (dateWeekNum < 4) {
				// 前移日期
				date2.setDate(date2.getDate() - dateWeekNum);
			} else {
				// 后移日期
				date2.setDate(date2.getDate() + 7 - dateWeekNum);
			}
			var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
			if (d < 0) {
				var date3 = date1.getFullYear() - 1 + '-12-31';
				return getYearWeek(date3);
			} else {
				// 得到年数周数
				var year = date1.getFullYear();
				var week = Math.ceil((d + 1) / 7);
				return week;
			}
		},

		// 获取每年 所有周的范围
		getAllWeekRange(year) {
			let weekNum = this.getWeekNum(year);
			let weeks = [];
			for (let index = 1; index <= weekNum; index++) {
				let range = this.getWeekRange(year, index, 1);
				let rangestr = '第' + index + '周';
				weeks.push({
					date: range,
					week: rangestr,
					year: year,
					value: index,
				});
			}
			return weeks;
		},
		// 确认
		submitDate() {
			if (this.dateCurr === 2) {
				let obj = this.weekList.find((item, i) => i === this.weekIndex);
				let arr = obj.date.replace(/['月','日']/g, '/').split('-');

				let str =
          obj.year +
          '/' +
          arr[0].substring(0, 5) +
          '-' +
          obj.year +
          '/' +
          arr[1].substring(0, 5);
				this.selectDate = str;
			}
			if (this.selectDate) {
				this.$emit('selectChange', { date: this.selectDate });
			}
			this.$refs.chooseDate.close();
		},
		dateFormat(times) {
			let date = new Date(times);
			let recent = '';
			if (times == this.today) {
				recent = '今天';
			} else if (times - this.today === 24 * 3600 * 1000) {
				recent = '明天';
			} else if (times - this.today === 2 * 24 * 3600 * 1000) {
				recent = '后天';
			}
			var year = date.getFullYear();
			var month =
        parseInt(date.getMonth() + 1) > 9
        	? parseInt(date.getMonth() + 1)
        	: '0' + parseInt(date.getMonth() + 1);
			var day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate();
			return {
				dateStr: year + '-' + month + '-' + day,
				week: '周' + this.weekList[date.getDay()],
				recent,
			};
		},
	},
};
</script>

<style lang="scss" scoped>
.popup-content {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  // height: 50px;
  background-color: #fff;
  border-radius: 8rpx 8rpx 0rpx 0rpx;

  .picker-view {
    width: 680rpx;
    height: 500rpx;
    margin-top: 20rpx;
    margin: 0 auto;
    position: relative;

    .colon {
      position: absolute;
      right: 20%;
      bottom: 47%;
    }

    .item {
      // height: 100rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      position: relative;

      .day {
        display: flex;
      }

      .date-left,
      .date-right {
        display: flex;
        flex: 1;
        justify-content: center;
      }

      .todayStr {
        width: 52rpx;
        height: 28rpx;
        background: #f3f6f8;
        border-radius: 4rpx;
        font-size: 20rpx;
        color: #0091ff;
      }
    }

    .item {}
  }

  /deep/.indicatorStyle {
    color: #0091ff;
  }

  .downs {
    width: 100%;

    .downs-btn {
      width: 64rpx;
      height: 10rpx;
      background: #d8d8d8;
      border-radius: 6rpx;
      margin: 0 auto;
    }
  }

  .bottoms {
    display: flex;
    height: 110rpx;
    align-items: center;
    border-top: 2rpx solid #eeeeee;

    view {
      display: flex;
      flex: 1;
      height: 70rpx;
      justify-content: center;
      align-items: center;
      font-size: 28rpx;
    }

    .reSet {
      background-color: #f5fbff;
      color: #0091ff;
      // margin-right: 10rpx;
      border-radius: 0rpx 8rpx 8rpx 0rpx;
    }

    .submit {
      background-color: $theme-color;
      color: #fff;
      border-radius: 0rpx 8rpx 8rpx 0rpx;
    }
  }
}
</style>
